package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.Accept;
import com.ruoyi.system.domain.File;
import com.ruoyi.system.domain.bo.FileBo;
import com.ruoyi.system.domain.vo.FileVo;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.mapper.AcceptMapper;
import com.ruoyi.system.mapper.FileMapper;
import com.ruoyi.system.mapper.SysOssMapper;
import com.ruoyi.system.service.IFileService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.ShareBo;
import com.ruoyi.system.domain.vo.ShareVo;
import com.ruoyi.system.domain.Share;
import com.ruoyi.system.mapper.ShareMapper;
import com.ruoyi.system.service.IShareService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 分享Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-02
 */
@RequiredArgsConstructor
@Service
public class ShareServiceImpl implements IShareService {

    private final ShareMapper baseMapper;
    private final FileMapper fileMapper;
    private final AcceptMapper acceptMapper;
    private final SysOssMapper sysOssMapper;

    /**
     * 查询分享
     */
    @Override
    public ShareVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public Share queryByCode(Long code) {
        ShareBo bo=new ShareBo();
        bo.setCode(code);
        LambdaQueryWrapper<Share> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoOne(lqw, Share.class);
    }

    /**
     * 查询分享列表
     */
    @Override
    public TableDataInfo<ShareVo> queryPageList(ShareBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Share> lqw = buildQueryWrapper(bo);
        Page<ShareVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        result.getRecords().forEach(x->{
            LambdaQueryWrapper<File> fileLQW=new LambdaQueryWrapper<>();
            fileLQW.eq(File::getShareId,x.getId());
            x.setFileCount(fileMapper.selectCount(fileLQW));
            x.setDownloadCount(fileMapper.selectVoList(fileLQW).stream().mapToLong(FileVo::getDownloadCount).sum());
            LambdaQueryWrapper<Accept> acceptLQW=new LambdaQueryWrapper<>();
            acceptLQW.eq(Accept::getShareId,x.getId());
            x.setAcceptCount(acceptMapper.selectCount(acceptLQW));
            if(x.getCreateTime()!=null&&x.getExp()!=null) {
                Date deadline = DateUtils.addDays(x.getCreateTime(), Integer.parseInt(x.getExp().toString()));
                x.setTimeDiff(DateUtils.differentDays(new Date(), deadline));
            }

        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询分享列表
     */
    @Override
    public List<ShareVo> queryList(ShareBo bo) {
        LambdaQueryWrapper<Share> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Share> buildQueryWrapper(ShareBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Share> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCode()!=null,Share::getCode, bo.getCode());
        lqw.eq(bo.getUserId()!=null,Share::getUserId, bo.getUserId());
        return lqw;
    }

    /**
     * 新增分享
     */
    @Override
    public Boolean insertByBo(ShareBo bo) {
        Share add = BeanUtil.toBean(bo, Share.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改分享
     */
    @Override
    public Boolean updateByBo(ShareBo bo) {
        Share update = BeanUtil.toBean(bo, Share.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Share entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除分享
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long genCode(ShareBo bo) {
        long code =  (long) ((Math.random() * 9 + 1) * 100000);
        bo.setCode(code);
        this.insertByBo(bo);
        String[] split = bo.getPaths().split(",");
        for (String s : split) {
            if(!StringUtils.isEmpty(s)){
                File file=new File();
                file.setShareId(bo.getId());
                file.setPath(s);
                fileMapper.insert(file);
            }
        }
        return code;
    }
}
